﻿using System;
using System.IO;
using System.Net.Sockets;
using System.Threading;
using System.Threading.Tasks;
using NModbus;
using NModbus.IO;
using NModbus.Message;

public class RtuOverTcpTransport : IStreamResource
{
    private NetworkStream _networkStream;
    private readonly TcpClient _tcpClient;

    public int InfiniteTimeout => int.MaxValue;  // 假设无限超时是最大整数值

    // 配置读取超时时间
    public int ReadTimeout { get; set; }

    // 配置写入超时时间
    public int WriteTimeout { get; set; }

    // 构造函数，传入 TcpClient 和 NetworkStream
    public RtuOverTcpTransport(NetworkStream networkStream)
    {
        //_tcpClient = tcpClient ?? throw new ArgumentNullException(nameof(tcpClient));
        _networkStream = networkStream;
        ReadTimeout = 1000;  // 默认 1 秒超时
        WriteTimeout = 1000; // 默认 1 秒超时
    }

    // 读取网络流数据
    public int Read(byte[] buffer, int offset, int count)
    {
        try
        {
            // 设置读取超时时间
            _networkStream.ReadTimeout = ReadTimeout;

            return _networkStream.Read(buffer, offset, count); // 从网络流读取数据
        }
        catch (IOException ex)
        {
            Console.WriteLine($"Read error: {ex.Message}");
            return -1; // 读取失败，返回错误码
        }
    }

    // 写入数据到网络流
    public void Write(byte[] buffer, int offset, int count)
    {
        try
        {
            // 设置写入超时时间
            _networkStream.WriteTimeout = WriteTimeout;

            _networkStream.Write(buffer, offset, count); // 向网络流写入数据
        }
        catch (IOException ex)
        {
            Console.WriteLine($"Write error: {ex.Message}");
        }
    }

    // 丢弃输入缓冲区的所有数据
    public void DiscardInBuffer()
    {
        byte[] discardBuffer = new byte[1024]; // 创建一个缓冲区来丢弃数据

        try
        {
            // 从网络流读取数据并丢弃
            while (_networkStream.DataAvailable)
            {
                _networkStream.Read(discardBuffer, 0, discardBuffer.Length);
            }
        }
        catch (IOException ex)
        {
            Console.WriteLine($"DiscardInBuffer error: {ex.Message}");
        }
    }

    // 释放资源，关闭连接
    public void Dispose()
    {
        try
        {
            _networkStream?.Close();
            _tcpClient?.Close();
        }
        catch (Exception ex)
        {
            Console.WriteLine($"Dispose error: {ex.Message}");
        }
    }
}
